import base64
from django_redis import get_redis_connection
import pickle


def merge_cookie_cart_to_redis(request, user,response):
    # 获取cookie中的数据　更换redis中的数据　都有的数据以cookie为主　
    cart_cookie = request.COOKIES.get('cart')
    if cart_cookie is None:
        return

    cart_dict = pickle.loads(base64.b64decode(cart_cookie))

    if not cart_dict:
        return

    # 将cookie中的数据按照redis中的存储方式存起来
    cart = {}
    # cookie中勾选的商品id
    cart_selected_add = []
    # cookie中未勾选的商品id
    cart_selected_remove = []

    for sku_id, cs_dict in cart_dict.items():
        cart[sku_id] =cs_dict['count']
        if cs_dict['selected'] == True:
            cart_selected_add.append(sku_id)
        else:
            cart_selected_remove.append(sku_id)

    # 合并
    user_id = user.id
    redis_conn = get_redis_connection('carts')
    cart_key = 'cart_%s' % user_id
    # hmset　存在就覆盖，不存在则创建
    cart_data = redis_conn.hmset(cart_key, cart)
    # 将`cart_selected_add`中商品id添加到redis 对应的set元素中
    cart_selected_key = 'cart_selected_%s' % user_id

    if cart_selected_add:
        redis_conn.sadd(cart_selected_key, *cart_selected_add)

    # 将`cart_selected_remove`中商品的id从redis 对应的set元素中移除
    if cart_selected_remove:
        redis_conn.srem(cart_selected_key, *cart_selected_remove)

    # 3. 删除cookie中购物车数据
    response.delete_cookie('cart')